import React, { useState, useEffect, useCallback } from 'react';
import { RouterProvider, Router } from 'react-router-dom';
import { Spin, Typography, Toast } from '@douyinfe/semi-ui';
import { createRouter, fallbackRouter } from './router';
import { routeRefreshManager } from './utils/routeRefresh';
import './App.css';

const App = () => {
  const [router, setRouter] = useState<Router | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshCount, setRefreshCount] = useState(0);

  // 路由初始化函数
  const initializeRouter = useCallback(async (showToast = false) => {
    try {
      setLoading(true);
      setError(null);
      
      // 检查是否有token，如果没有则直接使用备用路由
      const token = localStorage.getItem('token');
      if (!token) {
        setRouter(fallbackRouter);
        return;
      }
      
      // 创建动态路由
      const dynamicRouter = await createRouter();
      setRouter(dynamicRouter);
      
      if (showToast) {
        Toast.success('路由已更新');
      }
    } catch (err) {
      console.error('路由初始化失败:', err);
      const errorMessage = err instanceof Error ? err.message : '未知错误';
      setError(`路由初始化失败: ${errorMessage}`);
      
      // 使用备用路由
      setRouter(fallbackRouter);
      
      if (showToast) {
        Toast.error('路由更新失败，使用默认配置');
      }
    } finally {
      setLoading(false);
    }
  }, []);

  // 初始化路由
  useEffect(() => {
    initializeRouter();
  }, [initializeRouter]);

  // 注册路由刷新回调
  useEffect(() => {
    const unregister = routeRefreshManager.onRefresh(() => {
      console.log('收到路由刷新信号，重新初始化路由');
      setRefreshCount(prev => prev + 1);
      initializeRouter(true);
    });

    // 启动定期检查（每30秒检查一次）
    const stopPeriodicCheck = routeRefreshManager.startPeriodicCheck(30000);

    return () => {
      unregister();
      stopPeriodicCheck();
    };
  }, [initializeRouter]);

  // 监听登录状态变化，重新初始化路由
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'token') {
        console.log('检测到Token变化，重新初始化路由');
        // Token变化时重新初始化路由，而不是直接刷新页面
        initializeRouter(true);
      }
    };

    // 监听自定义的登录状态变化事件
    const handleLoginStateChange = () => {
      console.log('检测到登录状态变化，重新初始化路由');
      initializeRouter(true);
    };

    window.addEventListener('storage', handleStorageChange);
    window.addEventListener('loginStateChanged', handleLoginStateChange);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('loginStateChanged', handleLoginStateChange);
    };
  }, [initializeRouter]);

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        flexDirection: 'column'
      }}>
        <Spin size="large" />
        <Typography.Text style={{ marginTop: 16 }}>
          {refreshCount > 0 ? '正在更新路由...' : '正在初始化路由...'}
        </Typography.Text>
        {refreshCount > 0 && (
          <Typography.Text type="secondary" style={{ marginTop: 8 }}>
            路由更新次数: {refreshCount}
          </Typography.Text>
        )}
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        flexDirection: 'column',
        padding: '20px'
      }}>
        <Typography.Text type="danger" style={{ marginBottom: 16, textAlign: 'center' }}>
          {error}
        </Typography.Text>
        <Typography.Text type="secondary" style={{ textAlign: 'center' }}>
          正在使用备用路由配置...
        </Typography.Text>
        {refreshCount > 0 && (
          <Typography.Text type="tertiary" style={{ marginTop: 8, fontSize: '12px' }}>
            尝试次数: {refreshCount + 1}
          </Typography.Text>
        )}
      </div>
    );
  }

  if (!router) {
    return (
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column',
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        gap: '16px'
      }}>
        <Typography.Text type="danger">路由初始化失败</Typography.Text>
        {error && <Typography.Text type="secondary">{error}</Typography.Text>}
      </div>
    );
  }

  return <RouterProvider router={router} />;
};

export default App;
